package com.duowan.cms.service.user;

import java.util.Comparator;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.duowan.cms.common.domain.Page;
import com.duowan.cms.common.service.DoToDtoConvertorFactory;
import com.duowan.cms.common.util.ChineseCharactersUtil;
import com.duowan.cms.common.util.MailUtil;
import com.duowan.cms.domain.user.User;
import com.duowan.cms.domain.user.UserPower;
import com.duowan.cms.domain.user.rpst.UserPowerRepository;
import com.duowan.cms.domain.user.rpst.UserRepository;
import com.duowan.cms.dto.user.PowerInfo;
import com.duowan.cms.dto.user.UserInfo;
import com.duowan.cms.dto.user.UserPowerInfo;
import com.duowan.cms.dto.user.UserPowerSearchCriteria;
import com.duowan.cms.dto.user.UserSearchCriteria;

@Service("userService")
public class UserServiceImpl implements UserService {

    @Autowired
    private UserPowerRepository userPowerRepository;

    @Autowired
    private UserRepository userRepository;

    private static Logger logger = Logger.getLogger(UserService.class);

    /**
     *判断用户是否已经存在，存在返回true,不存在返回false;
     */
    @Override
    public boolean checkUserExist(String userId) {
        UserInfo userInfo = this.getById(userId);
        return userInfo != null;
    }

    @Override
    public List<UserPowerInfo> getAllPowerByUyserId(String userId) {
        return userPowerRepository.getAllPowerByUserId(userId);
    }

    @Override
    public UserInfo getById(String userId) {
        User user = userRepository.getById(userId);
        return (UserInfo) DoToDtoConvertorFactory.getConvertor(User.class).do2Dto(user);
    }

    @Override
    public UserInfo getByMail(String mail) {
        User user = userRepository.getByMail(mail);
        return (UserInfo) DoToDtoConvertorFactory.getConvertor(User.class).do2Dto(user);
    }

    @Override
    public UserPowerInfo getByUserIdAndChannelId(String userId, String channelId) {
        UserPower userPower = userPowerRepository.getByUserIdAndChannelId(userId, channelId);
        return (UserPowerInfo) DoToDtoConvertorFactory.getConvertor(UserPower.class).do2Dto(userPower);
    }

    @SuppressWarnings("unchecked")
    @Override
    public UserInfo getByUserIdAndPassword(String userId, String password) {
        User user = userRepository.getByUserIdAndPassword(userId, password);
        return (UserInfo) DoToDtoConvertorFactory.getConvertor(User.class).do2Dto(user);
    }
    
    @Override
    public UserInfo getByUdbName(String udbName) {
        User user = userRepository.getByUdbName(udbName);
        return (UserInfo) DoToDtoConvertorFactory.getConvertor(User.class).do2Dto(user);
    }

    @Override
    public void freeze(String userId) {
        User user = userRepository.getById(userId);
        user.freeze();
        userRepository.update(user);
        logger.info("成功冻结用户[uid=" + user.getUserId() + "]");
    }

    @Override
    public void unFreeze(String userId) {
        User user = userRepository.getById(userId);
        user.unfreeze();
        userRepository.update(user);
        logger.info("成功解冻用户[uid=" + user.getUserId() + "]");
    }

    @Override
    public void updateEmail(String userId, String email) {
        User user = userRepository.getById(userId);
        user.setMail(email);
        user.setLastModifyTime(new Date());
        userRepository.update(user);
        logger.info("更新用户[uid=" + user.getUserId() + "]的Email地址为" + email);
    }

    @Override
    public void updatePassword(String userId, String password) {
        User user = userRepository.getById(userId);
        user.setPassword(password);
        user.setLastModifyTime(new Date());
        userRepository.update(user);
        logger.info("用户[uid=" + user.getUserId() + "]更新密码成功");
    }

    @Override
    public void updateUserName(String oldName, String newName) {
        userRepository.updateName(oldName, newName);
        logger.info("用户[uid=" + oldName + "]更名为[uid=" + newName + "]成功");
    }

    @Override
    public Page<UserInfo> pageSearch(UserSearchCriteria searchCriteria) {
        return userRepository.pageSearch(searchCriteria);
    }

    @Override
    public Page<UserPowerInfo> pageSearch(UserPowerSearchCriteria searchCriteria) {
        return userPowerRepository.pageSearch(searchCriteria);
    }

    /**
     *  删除用户并把用户所有频道的权限删除
     *  注意：理论上来说，应该要删除用户在ArticleCount_db的数据,晓杰与壮秋讨论后，决定忽略这一部分
     */
    @Override
    public void deleteUser(String userId) {
        User user = userRepository.getById(userId);
        if (null != user) {
            userRepository.delete(user);
            userPowerRepository.deleteByUserId(userId);// deleteByIds(idList);
            logger.info("成功删除用户[uid=" + userId + "]，及其所有频道的权限");
        }
    }

    @Override
    public void deletePower(String userId, String channelId) {
        UserPower userPower = userPowerRepository.getByUserIdAndChannelId(userId, channelId);
        userPowerRepository.delete(userPower);
        logger.info("成功删除用户[uid=" + userId + "]在频道[channelId=" + channelId + "]下的权限");
    }

    @Override
    public void addUser(UserInfo userInfo, UserPowerInfo userPowerInfo) {
        User user = new User(userInfo);
        userRepository.save(user);
        this.addUserPower(userPowerInfo);
        logger.info("成功增加新用户[uid=" + userInfo.getUserId() + "]");
    }

    @Override
    public void updateUser(UserInfo userInfo) {
        this.updateUser(userInfo, null);
    }

    @Override
    public void updateUser(UserInfo userInfo, UserPowerInfo userPowerInfo) {
        User user = userRepository.getById(userInfo.getUserId());
        user.update(userInfo);
        userRepository.update(user);
        if (userPowerInfo != null) {
            this.updateUserPower(userPowerInfo);
        }
        logger.info("成功更新用户[uid=" + userInfo.getUserId() + "]的信息。");
    }

    @Override
    public void addUserPower(UserPowerInfo userPowerInfo) {
        UserPower userPower = new UserPower(userPowerInfo);
        userPowerRepository.save(userPower);
        logger.info("成功添加用户[uid=" + userPowerInfo.getUserId() + "]到频道[" + userPowerInfo.getChannelInfo().getName() + "]");
    }

    @Override
    public void updateUserPower(UserPowerInfo userPowerInfo) {
        UserPower userPower = userPowerRepository.getByUserIdAndChannelId(userPowerInfo.getUserId(), userPowerInfo.getChannelId());
        userPower.update(userPowerInfo);
        userPowerRepository.update(userPower);
        logger.info("成功更新用户[uid=" + userPowerInfo.getUserId() + "]在频道[" + userPowerInfo.getChannelInfo().getName() + "]的权限");
    }

    @Override
    public boolean hasPower(String channelId, UserInfo userInfo, String powerId) {

        UserPowerInfo userPowerInfo = null;

        List<UserPowerInfo> powerList = userInfo.getAllChannelPowerInfo();
        if (null != powerList) {
            userPowerInfo = getUserPowerInfoFromList(powerList, channelId);
        } else {
            userPowerInfo = this.getByUserIdAndChannelId(userInfo.getUserId(), channelId);
        }

        if (userPowerInfo != null) {
            List<PowerInfo> powerInfos = userPowerInfo.getOwnPowers();
            for (int i = 0; i < powerInfos.size(); i++) {
                if (powerId.trim().equals(powerInfos.get(i).getId()))
                    return true;
            }
        }
        return false;
    }

    // 从权限列表中查找某个频道的权限
    private UserPowerInfo getUserPowerInfoFromList(List<UserPowerInfo> powerList, String channelId) {
        for(UserPowerInfo upi : powerList){
            if(channelId.equals(upi.getChannelId()))
                return upi;
        }
        return null;
    }

    @Override
    public void sendMessageToMail(String mailTo, String title, String content) throws Exception {
        MailUtil.sendHtmlEmail(mailTo, title, content);
    }

}
